package movieGandalf.DB;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class CountriesReader implements DataReader{
	
	public int read(Connection conn, InputStream in){
		String line = null;
		Set<String> countries = new HashSet<String>();
		
		try {
			boolean isBegin = true;
			while ((line = MovieTools.getLine(in)) != null){
				if (isBegin){
					if ((line.length()<3 || !line.subSequence(0, 3).equals("===")))
						continue;
					else{
						isBegin = false;
						continue;
					}
				}
				
				int i = 0;
				for (i = line.length()-1;i>=0;i--){
					if (line.charAt(i)=='\t'){
						i++;
						break;
					}
				}
				
				if (i==-1)
					continue;
				
				countries.add(line.substring(i, line.length()));
			}
			

			PreparedStatement stmt = conn.prepareStatement(new String("REPLACE INTO Countries (country) VALUES (?)"));
			
			Iterator<String> iter = countries.iterator();
			String country = null;
			
			while (iter.hasNext()){
				country = iter.next();
				stmt.setString(1, country);
				stmt.addBatch();
			}
			int[] res = stmt.executeBatch();
			conn.commit();
			stmt.close();
		}
		
		catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			try{
				in.close();
			}
			catch(Exception e){
				return 0;
			}
		}
		
		return 1;
	}
	
}
